package jprint.jfx.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import jprint.base.http.AbstractRequestHandler;
import jprint.base.http.Http;

/**
 * @author zw-zheng
 * Created on 2020-11-22
 */
public class AssetsFileHandler extends AbstractRequestHandler {

    private static final String[] allowUriPrefix = {
        "/css/",
        "/images/",
        "/js/",
    };
    private final File baseDir;

    public AssetsFileHandler(File baseDir) {
        this.baseDir = baseDir;
    }

    @Override public boolean handle(Http.HttpRequest request, Http.HttpResponse response) {
        if (request.method() != Http.Method.GET) return false;
        String uri = request.uri();
        if (uri == null || uri.length() == 1) {
            uri = "/index.html";
        }

        if (fileReg.matcher(uri).matches() && allowAccessUri(uri)) {
            String fileName = uri.charAt(0) == '/' ? uri : "/" + uri;
            try {
                response.setContentType(contentTypeOf(uri))
                    .write(new FileInputStream(new File(baseDir, fileName)));
            } catch (IOException e) {
                e.printStackTrace();
                send50x(response);
            }
            return true;
        }
        return false;
    }

    private static boolean allowAccessUri(String uri) {
        if (uri.lastIndexOf('/') == 0) { // only one slash at beginning
            return true;
        }
        for (String prefix : allowUriPrefix) {
            if (uri.startsWith(prefix)) {
                return true;
            }
        }
        return false;
    }
}
